<template>
  <div class="enterprise">
    <el-form ref="form" label-width="130px">
      <el-form-item label="企业名称:">
        <el-input
          v-model.trim="infoData.enterpriseName"
          size="small"
          :disabled="infoData.enterpriseType == 1"
        ></el-input>
      </el-form-item>
      <el-form-item label="社会统一信用代码:">
        <el-input v-model.trim="infoData.companyCode" size="small" :disabled="infoData.enterpriseType == 1"></el-input>
      </el-form-item>
      <el-form-item label="工商注册地:">
        <div class="datebox">
          <el-select
            style="width: 110px"
            size="small"
            :disabled="infoData.enterpriseType == 1"
            v-model.trim="infoData.province"
            placeholder="请选择"
            @change="provinceChange"
          >
            <el-option
              v-for="item in provinceOptions"
              :key="item.provinceId"
              :label="item.province"
              :value="item.provinceId"
            >
            </el-option>
          </el-select>
          <el-select
            style="width: 110px; margin-left: 10px"
            size="small"
            :disabled="infoData.enterpriseType == 1"
            value-key="cityId"
            v-model.trim="infoData.city"
            placeholder="请选择"
            @change="cityChange"
          >
            <el-option v-for="item in cityOptions" :key="item.cityId" :label="item.city" :value="item.cityId">
            </el-option>
          </el-select>
          <el-select
            style="width: 110px; margin-left: 10px"
            size="small"
            :disabled="infoData.enterpriseType == 1"
            v-model.trim="infoData.area"
            placeholder="请选择"
            @change="areaChange"
          >
            <el-option v-for="item in areaOptions" :key="item.areaId" :label="item.area" :value="item.areaId">
            </el-option>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="单位法人:">
        <el-input v-model.trim="infoData.legalPerson" size="small" :disabled="infoData.enterpriseType == 1"></el-input>
      </el-form-item>
      <el-form-item label="业务联系人:">
        <el-input v-model.trim="infoData.contacts" size="small" :disabled="infoData.enterpriseType == 1"></el-input>
      </el-form-item>
      <el-form-item label="联系人手机:">
        <el-input v-model.trim="infoData.phone" size="small" :disabled="infoData.enterpriseType == 1"></el-input>
      </el-form-item>
      <el-form-item label="企业类型:">
        <el-select
          v-model.trim="infoData.enterpriseProfitType"
          placeholder="请选择"
          size="small"
          :disabled="infoData.enterpriseType == 1"
        >
          <el-option v-for="item in typeOptions" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="企业性质:">
        <el-select
          v-model.trim="infoData.enterpriseNature"
          placeholder="请选择"
          size="small"
          :disabled="infoData.enterpriseType == 1"
        >
          <el-option v-for="item in natureOptions" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="营业期限:">
        <div class="datebox">
          <el-date-picker
            v-model.trim="infoData.businessStart"
            align="right"
            type="date"
            value-format="yyyy-MM-dd"
            size="small"
            :disabled="infoData.enterpriseType == 1"
            placeholder="选择日期"
          >
          </el-date-picker>
          <span style="margin: 0 10px">至</span>
          <el-date-picker
            v-model.trim="infoData.businessEnd"
            align="right"
            :disabled="infoData.enterpriseType == 1"
            value-format="yyyy-MM-dd"
            size="small"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </div>
        <p style="color: #fa7355; line-height: 30px">提示：营业期限结束日期为空，代表长期。</p>
      </el-form-item>
      <el-form-item label="纳税人资格:">
        <el-select
          v-model.trim="infoData.taxpayerQualification"
          placeholder="请选择"
          size="small"
          :disabled="infoData.enterpriseType == 1"
        >
          <el-option v-for="item in taxpayerOptions" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="主要物资类别:" v-if="enterpriseType != 1">
        <el-input
          style="width: 220px"
          class="no_border"
          disabled
          size="small"
          placeholder="请选择"
          v-model.trim="infoData.materialType"
        >
          <el-button @click="selectMaterial" slot="append">选择</el-button>
        </el-input>
        <!-- <el-input v-model.trim="infoData.materialType" size="small"></el-input> -->
      </el-form-item>
      <el-form-item label="营业执照扫描件">
        <div style="display: flex; align-items: center">
          <el-input
            disabled
            v-model="fileName"
            placeholder="限PDF、JPG、PNG格式，单张不可超过10M"
            size="small"
            style="width: 280px"
          ></el-input>
          <el-button
            size="small"
            class="exportBtn"
            style="margin-left: 10px; height: 32px"
            @click="upFile"
            :disabled="enterpriseType == 1"
            >上传扫描件</el-button
          >
        </div>
        <div class="upload-wrap">
          <el-upload
            class="upload-demo"
            :headers="loadHeader"
            :action="urlUpload"
            :show-file-list="false"
            :limit="1"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
            :on-exceed="onExceed"
            accept=".png,.jpg,.pdf"
          >
            <template slot="trigger">
              <div ref="biddUpload"></div>
            </template>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="" style="margin-top: 32px; margin-bottom: 0">
        <el-button size="small" class="commonBtn1" style="width: 280px" @click="subMit" v-if="enterpriseType != 1">
          提交
        </el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      class="dialog_detail"
      :center="true"
      :close-on-click-modal="false"
      width="1200px"
      title="请选择物资类别"
      :visible.sync="materialVisible"
    >
      <label for="">品类检索:</label>
      <el-cascader
        style="width: 580px; margin-left: 10px"
        size="small"
        v-model.trim="searchValue"
        ref="searchCascader"
        :options="materialList"
        @change="searchChange"
        :props="{
          checkStrictly: true,
          value: 'id',
          label: 'materialName',
          children: 'son'
        }"
        filterable
      ></el-cascader>
      <div class="dialog_box">
        <div class="left">
          <p
            v-for="(item, index) in materialList"
            :key="index"
            :class="firstIndex == index ? 'on' : ''"
            @click="firstClick(index)"
          >
            {{ item.materialName }}
          </p>
        </div>
        <div class="center">
          <p v-for="(item, index) in materialDetailList" :key="index">
            {{ item.materialName }}
            <el-checkbox v-model.trim="item.isHave" @change="secondChange($event, index)"></el-checkbox>
          </p>
        </div>
        <div class="right">
          <div v-for="(item, index) in materialShowList" :key="index">
            {{ item.materialName }}
            <i @click="removeMaterial(index)" class="iconfont icon-guanbi"></i>
          </div>
        </div>
      </div>
      <div class="footer">
        <button class="no_btn" @click="closeBtn">取消</button>
        <button class="ok_btn" @click="okBtn">确定</button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      enterpriseType: localStorage.getItem('enterpriseType'),
      fileSuccess: true,
      fileName: '',
      timer: null,
      urlUpload: this.GLOBAL.weburl + '/api/file/upload',
      infoData: {},
      value: '',
      typeOptions: [
        {
          dictKey: 0,
          dictValue: '国营'
        },
        {
          dictKey: 1,
          dictValue: '民营'
        },
        {
          dictKey: 2,
          dictValue: '外资'
        },
        {
          dictKey: 3,
          dictValue: '合资'
        },
        {
          dictKey: 4,
          dictValue: '个体工商户'
        }
      ],
      natureOptions: [
        {
          dictKey: 0,
          dictValue: '贸易商'
        },
        {
          dictKey: 1,
          dictValue: '代理商'
        },
        {
          dictKey: 2,
          dictValue: '生产商'
        }
      ],
      taxpayerOptions: [
        {
          dictKey: 0,
          dictValue: '增值税一般纳税人'
        },
        {
          dictKey: 1,
          dictValue: '增值税小规模纳税人'
        },
        {
          dictKey: 2,
          dictValue: '非增值税纳税人'
        }
      ],
      provinceOptions: [],
      cityOptions: [],
      areaOptions: [],
      materialVisible: false,
      materialList: [],
      materialDetailList: [],
      materialShowList: [],
      materialTypeIds: [],
      materialShowListCopy: [],
      firstIndex: 0,
      searchValue: ''
    }
  },
  mounted() {
    //调用公共方法获取省列表
    this.common.getAddressList('province').then(value => {
      this.provinceOptions = value
      this.getData()
    })
  },
  computed: {
    loadHeader() {
      let token = this.common.getCookie('materialsToken')
      const header = {}
      header[this.GLOBAL.tokenName] = token
      return header
    }
  },
  methods: {
    //上传附件
    upFile() {
      this.$refs.biddUpload.click()
    },
    // 文件上传前进行文件大小检测
    beforeUpload(file) {
      this.fileSuccess = false
      const isLt = file.size / 1024 / 1024 / 10 <= 1
      if (!isLt) {
        this.$message.error('单个文件大小不能超过10M,请检查文件大小并重新尝试')
      }
      return isLt
    },
    // 文件上传前判断是否超过上传文件个数限制
    onExceed() {
      this.$message.error('最多支持上传1个文件')
    },
    // 上传成功时的回调
    uploadSuccess(val, e, el) {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.$message.success('上传成功')
      }, 0)
      this.fileSuccess = true
      this.fileName = e.name
      this.infoData.businessLicense = e.response.data
    },
    //删除已选择物资
    removeMaterial(index) {
      for (let i = 0; i < this.materialDetailList.length; i++) {
        if (this.materialDetailList[i].materialName == this.materialShowList[index].materialName) {
          this.materialShowList.splice(index, 1)
          this.materialShowListCopy.splice(index, 1)
          this.$set(this.materialDetailList[i], 'isHave', false)
          // this.materialDetailList[i].isHave = false;
          return false
        }
      }
    },
    filteArr(item, arr) {
      let indexs = null
      arr.forEach((el, index) => {
        if (el.oneLevelId == item.fatherId) {
          indexs = index
        }
      })
      if (indexs == null) {
        arr.push({
          oneLevelId: item.fatherId,
          twoLevelId: item.id + ','
        })
      } else {
        arr[indexs].twoLevelId += item.id + ','
      }
    },
    //物资确认按钮
    okBtn() {
      this.materialShowListCopy = JSON.parse(JSON.stringify(this.materialShowList))
      let text = ''
      for (let i = 0; i < this.materialShowListCopy.length; i++) {
        text += this.materialShowListCopy[i].materialName + '、'
        this.filteArr(this.materialShowListCopy[i], this.materialTypeIds)
      }
      this.materialTypeIds.forEach(item => {
        const str = item.twoLevelId.substr(0, item.twoLevelId.length - 1)
        this.$set(item, 'twoLevelId', str)
      })
      this.infoData.materialType = text.substr(0, text.length - 1)
      this.materialVisible = false
    },
    //取消按钮
    closeBtn() {
      this.materialVisible = false
    },
    //搜索事件
    searchChange(e) {
      for (let i = 0; i < this.materialList.length; i++) {
        if (this.materialList[i].id == e[0]) {
          this.firstClick(i)
          if (e.length == 2) {
            for (let j = 0; j < this.materialList[i].son.length; j++) {
              if (this.materialList[i].son[j].id == e[1] && !this.materialList[i].son[j].isHave) {
                this.materialList[i].son[j].isHave = true
                this.materialShowList.push(this.materialList[i].son[j])
              }
            }
          }
        }
      }
      this.$nextTick(() => {
        this.$refs.searchCascader.$refs.panel.clearCheckedNodes()
        this.$refs.searchCascader.$refs.panel.activePath = []
        this.$refs.searchCascader.dropDownVisible = false
      })
    },
    //选择物资类别按钮
    selectMaterial() {
      this.$https({
        method: 'post',
        url: '/material/listAllMaterial',
        data: {}
      })
        .then(res => {
          if (res.code === 0) {
            this.materialList = res.data
            for (let i = 0; i < this.materialList.length; i++) {
              for (let j = 0; j < this.materialList[i]['son'].length; j++) {
                this.$set(this.materialList[i]['son'][j], 'son', null)
              }
            }
            this.firstClick(0)
            this.materialVisible = true
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    //物资一级点击事件
    firstClick(index) {
      this.firstIndex = index
      this.materialDetailList = this.materialList[index].son
      for (let i = 0; i < this.materialShowListCopy.length; i++) {
        for (let j = 0; j < this.materialDetailList.length; j++) {
          if (this.materialShowListCopy[i].id == this.materialDetailList[j].id) {
            this.materialDetailList[j].isHave = true
          }
        }
      }
    },
    //物资二级勾选事件
    secondChange(e, index) {
      if (e) {
        this.materialShowList.push(this.materialDetailList[index])
      } else {
        for (let i = 0; i < this.materialShowList.length; i++) {
          if (this.materialShowList[i].materialName == this.materialDetailList[index].materialName) {
            this.materialShowList.splice(i, 1)
          }
        }
      }
    },
    subMit() {
      if (!this.fileSuccess) {
        this.$message.error('请等待文件上传完毕')
        return false
      }
      console.log(this.infoData)
      if (!this.infoData.enterpriseName) {
        this.$message.error('请输入企业名称')
      } else if (this.infoData.enterpriseNature === '' || this.infoData.enterpriseNature == null) {
        console.log(this.infoData.enterpriseNature == '')
        console.log(this.infoData.enterpriseNature == null)
        this.$message.error('请选择企业性质')
      } else if (!this.infoData.companyCode) {
        this.$message.error('请输入社会统一信用代码')
      } else if (!this.infoData.businessStart) {
        this.$message.error('请选择营业期限')
      } else if (!this.infoData.province || !this.infoData.city || !this.infoData.area) {
        this.$message.error('请选择工商注册地')
      } else if (this.infoData.taxpayerQualification === '' || this.infoData.taxpayerQualification == null) {
        this.$message.error('请选择纳税人资格')
      } else if (!this.infoData.legalPerson) {
        this.$message.error('请输入单位法人')
      } else if (!this.infoData.contacts) {
        this.$message.error('请输入业务联系人')
        // } else if (this.materialShowListCopy.length == 0) {
        //   this.$message.error("请选择主营物资类别");
      } else if (!this.infoData.phone) {
        this.$message.error('请输入联系人手机')
      } else if (!this.common.fieldTest('phone', this.infoData.phone)) {
        this.$message.error('请输入正确的手机号')
      } else if (this.infoData.enterpriseProfitType === '' || this.infoData.enterpriseProfitType == null) {
        this.$message.error('请选择企业类型')
      } else if (!this.infoData.businessLicense) {
        this.$message.error('请上传营业执照')
      } else {
        this.infoData.userId = parseInt(localStorage.getItem('userId'))
        // this.infoData.businessStart = this.startTime;
        // this.infoData.businessEnd = this.endTime;
        // let text = "";
        // for (let i = 0; i < this.materialShowListCopy.length; i++) {
        //   text += this.materialShowListCopy[i].materialName + ",";
        // }
        // this.infoData.materialType = text.substr(0, text.length - 1);
        this.$https({
          method: 'post',
          url: '/User/InformationPerfection',
          data: { ...this.infoData, materialTypeIds: this.materialTypeIds }
        })
          .then(res => {
            if (res.code === 0) {
              this.$message.success(res.msg)
              this.getData()
              // this.$router.push("/");
            } else {
              this.$message.error(res.msg)
            }
          })
          .catch(err => {
            console.log(err)
          })
      }
    },
    areaChange(e) {
      let arr = this.areaOptions.filter(item => {
        return item.areaId == e
      })
      if (arr.length) {
        this.infoData.areaName = arr[0]['area']
      }
    },
    //选完省后获取市
    provinceChange(e) {
      let arr = this.provinceOptions.filter(item => {
        return item.provinceId == e
      })
      if (arr.length) {
        this.infoData.provinceName = arr[0]['province']
      }
      this.infoData.city = ''
      this.infoData.area = ''
      this.common.getAddressList('city', e).then(value => {
        this.cityOptions = value
      })
    },
    //选完市后获取区
    cityChange(e) {
      let arr = this.cityOptions.filter(item => {
        return item.cityId == e
      })
      if (arr.length) {
        this.infoData.cityName = arr[0]['city']
      }
      this.infoData.area = ''
      this.common.getAddressList('area', e).then(value => {
        this.areaOptions = value
      })
    },
    getData() {
      this.$https({
        method: 'post',
        url: '/User/informationByEnterpriseId?enterpriseId=' + localStorage.getItem('enterpriseId')
      })
        .then(res => {
          if (res.code === 0) {
            this.provinceChange(res.data.enterprise.province)
            this.cityChange(res.data.enterprise.city)
            this.infoData = res.data.enterprise
            this.infoData.businessLicense = this.infoData.businessLicense || ''
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>
<style lang="less" scoped>
.dialog_detail {
  /deep/.el-input {
    width: 280px !important;
  }
}
.dialog_box {
  width: 100%;
  margin-top: 30px;
  display: flex;
  justify-content: space-between;
  .on {
    background-color: #fee3dd;
  }
  .left {
    width: 350px;
    height: 490px;
    overflow-y: auto;
    border: 1px solid #d6d6d6;
    p {
      padding: 10px 20px;
      box-sizing: border-box;
      font-size: 14px;
      cursor: pointer;
    }
  }
  .center {
    width: 350px;
    height: 490px;
    overflow-y: auto;
    margin: 0 20px;
    border: 1px solid #d6d6d6;
    p {
      padding: 10px 20px;
      box-sizing: border-box;
      font-size: 14px;
      cursor: pointer;
      .el-checkbox {
        float: right;
      }
    }
  }
  .right {
    width: 400px;
    height: 490px;
    overflow-y: auto;
    padding: 10px 10px;
    box-sizing: border-box;
    border: 1px solid #d6d6d6;
    div {
      display: inline-block;
      padding: 5px 10px;
      font-size: 14px;
      box-sizing: border-box;
      border: 1px solid #d6d6d6;
      border-radius: 5px;
      margin: 10px 10px;
      .iconfont {
        font-size: 12px;
        cursor: pointer;
      }
    }
  }
}
.footer {
  width: 100%;
  margin-top: 20px;
  text-align: center;
  .no_btn {
    width: 130px;
    height: 32px;
    border: 1px solid #fa7355;
    color: #fa7355;
    background-color: #fff;
    border-radius: 5px;
    cursor: pointer;
  }
  .no_btn:hover {
    background-color: #fa7355;
    color: #fff;
  }
  .ok_btn {
    width: 130px;
    height: 32px;
    background-color: #fa7355;
    border-radius: 5px;
    margin-left: 20px;
    color: #fff;
    cursor: pointer;
  }
  .ok_btn:hover {
    background-color: rgba(250, 115, 85, 0.85);
  }
}
.upload-wrap {
  /deep/.el-upload {
    display: none;
  }
  /deep/.el-upload-list {
    display: flex;
    align-items: center;
    width: 600px;
    flex-wrap: wrap;
    margin-bottom: 20px;
    .el-upload-list__item {
      width: 260px;
      margin: 20px 30px 0 0;
      background: #f0f1f2;
      border: 1px solid #d6d6d6;
    }
    .el-icon-close {
      &:hover {
        color: #fa7355;
      }
    }
  }
}
.enterprise {
  .datebox {
    display: flex;
    /deep/.el-input__inner {
      width: 100%;
    }
  }
  /deep/.el-form-item {
    margin-bottom: 12px;
  }
  /deep/.el-input__inner {
    width: 280px;
  }
}
</style>
